# coding:utf8
'''
    订单相关
'''
from flask_restful import Resource, request
from _sys.models import MongodbOperations, ResponseJson, Token, CreateId, FormatIO
from _sys.code import dbNameDict, typeDict
from _sys.function import format_words, parse_param_info, allow_cross,calculating_order_amount,calculating_product_activity_price
from _sys.parser import parsers

responseJson = ResponseJson()
token = Token()
mgOp = MongodbOperations()
cId = CreateId()

import time

class Order(Resource):
    '''
        /order
        -- get 获取订单信息 用户或者管理员
        -- post 修改订单信息 管理员
        -- put 新增订单 用户
        -- delete 删除订单  禁用，保留接口
    '''
    @allow_cross
    def get(self):
        args = parsers()
        u_id = args.get('u_id')
        u_token = args.get('u_token')
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        o_id = args.get('o_id')

        if u_id and u_token: # 用户
            if token.verify(u_token, u_id):
                if o_id:
                    o_data = mgOp.find_one(dbNameDict['userOrderData'], {'o_id': o_id})
                    if o_data:
                        temp = o_data
                        return responseJson.correct(code='ok', data=temp)
                    else:
                        return responseJson.error_response(code='resourcesDoNotExist')
                else:
                    o_data = mgOp.find_many(dbNameDict['userOrderData'], {'u_id': u_id})
                    if o_data:
                        temp = o_data
                        return responseJson.correct(code='ok', data=temp)
                    else:
                        return responseJson.error_response(code='resourcesDoNotExist')
            else:
                return responseJson.error_response(code='tokenFailure')
        elif a_id and a_token: # 管理员
            if token.verify(a_token, a_id):
                if o_id:
                    o_data = mgOp.find_one(dbNameDict['userOrderData'], {'o_id': o_id})
                    if o_data:
                        temp = o_data
                        return responseJson.correct(code='ok', data=temp)
                    else:
                        return responseJson.error_response(code='resourcesDoNotExist')
                else:
                    o_data = mgOp.find_many(dbNameDict['userOrderData'], {})
                    if o_data:
                        temp = o_data
                        return responseJson.correct(code='ok', data=temp)
                    else:
                        return responseJson.error_response(code='resourcesDoNotExist')
            else:
                return responseJson.error_response(code='tokenFailure')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')


    @allow_cross
    def put(self):
        '''
            创建订单
            1: 会员创建
            2: 不记名用户创建
        :return:
        '''
        args = parsers()
        t = args.get('type')   # 普通 或者 客制化
        u_id = args.get('u_id')
        u_addr = args.get('u_addr')
        pay_way = args.get('way')  # 付款途径
        u_phone = args.get('u_phone')
        u_mail = args.get('u_mail')
        u_name = args.get('u_name')
        u_sex = args.get('u_sex')
        lang = args.get('lg')
        if u_id:   # 会员创建
            u_token = args.get('u_token')
            pids = args.get('p_id')   # pid.size|pid.size|pid.size
            if token.verify(u_token, u_id):
                query_time = time.strftime("%Y%m%d", time.localtime())   # 筛选时间
                #print(query_time)
                num = mgOp.find_many(dbNameDict['userOrderData'], filter={'query_time': query_time})  # 统计当天订单数
                o_id = cId.oid(typeDict[t], len(num))   # 创建订单编号
                is_vip = mgOp.find_one(dbNameDict['userData'],filter={'u_id':u_id})['is_vip']    # 调查用户是否vip
                order_amount = 0
                if int(is_vip):   # 是vip
                    p_datas = []
                    for pid in pids.split('|'):
                        if pid:
                            p_id = pid.split('.')[0]
                            size = pid.split('.')[1]
                            count = pid.split('.')[2]
                            p_data = mgOp.find_one(dbNameDict['productData'],
                                                              filter={'p_id': p_id})  # 获得商品数据并删除购物车
                            if mgOp.find_one(dbNameDict['userCartData'], filter={'p_id': p_id}):
                                mgOp.delete_one(dbNameDict['userCartData'], filter={'p_id': p_id, 'p_size': size})

                            p_data['p_size'] = size
                            p_data['p_count'] = count
                            p_data['act_price'] = calculating_product_activity_price(pid, lang ,is_vip=True)  # 商品价格按照vip重新计算
                            order_amount = order_amount + float(p_data['act_price']) * int(count)
                            p_data['amount'] = float(p_data['act_price']) * int(count)
                            p_datas.append(p_data)
                else:           # 不是 vip
                    p_datas = []
                    print(pids)
                    print(pids.split('|'))
                    for pid in pids.split('|'):
                        if pid:
                            p_id = pid.split('.')[0]
                            size = pid.split('.')[1]
                            count = pid.split('.')[2]
                            p_data = mgOp.find_one(dbNameDict['productData'],
                                                   filter={'p_id': p_id})  # 获得商品数据并删除购物车
                            if mgOp.find_one(dbNameDict['userCartData'], filter={'p_id': p_id}):
                                mgOp.delete_one(dbNameDict['userCartData'], filter={'p_id': p_id, 'p_size': size})

                            p_data['p_size'] = size
                            p_data['p_count'] = count
                            p_data['act_price'] = p_data['p_price']
                            p_data['amount'] = float(p_data['p_price'][lang]) * int(count)
                            order_amount = order_amount + float(p_data['p_price'][lang]) * int(count)
                            p_datas.append(p_data)

                new_order = {
                    'u_id': u_id,
                    'o_id': o_id,
                    'send_name':u_name,
                    'send_sex':u_sex,
                    'status':'0',    # unpay
                    'status_name':'unpay',
                    'create_time': str(time.time()),
                    'format_time': FormatIO().timestamp_format(time.time()),
                    'query_time': str(query_time),      # 精确到天
                    'product_data': p_datas,
                    'send_addr':u_addr,
                    'send_phone': u_phone,
                    'send_mail':u_mail,
                    'pay_method':pay_way,   # 付款方式
                    'pay_status':'0',  # 付款状态
                    'express_num':'',   # 物流单号
                    'express_com':'',   # 物流公司
                    'order_amount': str(order_amount),
                    'act_price':'',
                }

                if mgOp.insert_one(dbNameDict['userOrderData'], data=new_order):
                    s = {
                         'act_price': calculating_order_amount(o_id)
                     }
                    rd = mgOp.find_one_and_update(dbNameDict['userOrderData'], filter={'o_id':o_id}, new_data=s)
                    return responseJson.correct(code='ok', data={'oid': o_id})
                else:
                    return responseJson.error_response(code='unknownError')
            else:
                return responseJson.error_response(code='tokenFailure')
        else:   # 非会员
            pids = args.get('p_id').split('|')
            nums = args.get('num').split('|')   #2|1|3
            for pid in pids:
                info = {
                    'p_id': pid,
                    'p_count': nums[pids.index(pid)]
                }
                p_data = mgOp.find_one(dbNameDict['productData'], filter={'p_id': pid})

    def post(self):
        '''
            支付订单验证 修改订单信息(管理员)
        :return:
        '''
        args = parsers()
        oid = args.get('o_id')
        payment = args.get('payment')
        rd = mgOp.find_one_and_update(dbNameDict['userOrderData'], filter={'o_id': oid}, new_data={'payment':payment, 'pay_status':'1'})
        return responseJson.correct(code='ok', data=rd['o_id'])


